package com.wfh.picture.manager.websocket.disruptor;

import cn.hutool.json.JSONUtil;
import com.lmax.disruptor.WorkHandler;
import com.wfh.picture.manager.websocket.PictureEditHandler;
import com.wfh.picture.manager.websocket.model.PictureEditMessageTypeEnum;
import com.wfh.picture.manager.websocket.model.PictureEditRequestMessage;
import com.wfh.picture.manager.websocket.model.PictureEditResponseMessage;
import com.wfh.picture.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

/**
 * @Author FengHuan Wang
 * @Date 2025/5/18 10:33
 * @Version 1.0
 */
@Component
@Slf4j
public class PictureEditEventWorkeHandler implements WorkHandler<PictureEditEvent> {


    @Resource
    @Lazy
    private PictureEditHandler pictureEditHandler;


    @Override
    public void onEvent(PictureEditEvent pictureEditEvent) throws Exception {
        // 获取消息列别
        Long pictureId = pictureEditEvent.getPictureId();
        WebSocketSession session = pictureEditEvent.getSession();
        PictureEditRequestMessage pictureEditRequestMessage = pictureEditEvent.getPictureEditRequestMessage();
        String type = pictureEditRequestMessage.getType();
        User user = pictureEditEvent.getUser();
        PictureEditMessageTypeEnum enumByValue = PictureEditMessageTypeEnum.getEnumByValue(type);
        switch (enumByValue) {
            case ENTER_EDIT:
                // 进入编辑
                pictureEditHandler.enterEdit(pictureEditRequestMessage, session, user, pictureId);
                break;
            case EXIT_EDIT:
                // 退出编辑
                pictureEditHandler.exitEdit(pictureEditRequestMessage, session, user, pictureId);
                break;
            case EDIT_ACTION:
                // 编辑动作
                pictureEditHandler.editAction(pictureEditRequestMessage, session, user, pictureId);
                break;
            default:
                // 其他消息，构建错误消息响应
                PictureEditResponseMessage pictureEditResponseMessage = new PictureEditResponseMessage();
                pictureEditResponseMessage.setType(PictureEditMessageTypeEnum.ERROR.getValue());
                pictureEditResponseMessage.setMessage("未知消息类型");
                // 发送消息
                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(pictureEditResponseMessage)));
                break;
        }
    }
}
